using HtmlAgilityPack;
using System.Net;

namespace 第七次作业
{
    public partial class Form1 : Form
    {
        private SearchHandler searchHandler;
        public Form1()
        {
            searchHandler = new SearchHandler();
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine(11);
            button1.Enabled = false;
            string keyword = textBox1.Text;
            try
            {
                string summary = await GetBaikeSummaryAsync("https://baike.baidu.com/item/" + keyword);
                textBox2.Text = summary.Substring(0, Math.Min(summary.Length, 100));
                if (summary.Length > 100)
                {
                    textBox3.Text = summary.Substring(100, Math.Min(summary.Length - 100, 100));
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            button1.Enabled = true;
        }

        private async Task<string> GetBaikeSummaryAsync(string url)
        {
            // 创建WebClient实例
            using (WebClient client = new WebClient())
            {

                // 设置编码方式，防止中文乱码
                client.Encoding = System.Text.Encoding.UTF8;

                // 异步发送GET请求，获取页面内容
                string content = await client.DownloadStringTaskAsync(url);

                // 使用HtmlAgilityPack解析页面内容
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content);

                // 获取词条内容
                HtmlNode summaryNode = doc.DocumentNode.SelectSingleNode("//div[@class='lemma-summary J-summary']");
                if (summaryNode != null)
                {
                    string summary = summaryNode.InnerText.Trim();
                    // 输出词条内容
                    return summary;
                }
                else
                {
                    return "search fail";
                }

            }
        }
    }
}